package com.bridgeintelligent.tag.combination.controller;

import com.alibaba.fastjson.JSON;
import com.bridgeintelligent.tag.combination.entity.CombinationCodes;
import com.bridgeintelligent.tag.combination.entity.Result;
import com.bridgeintelligent.tag.combination.exception.CombinationException;
import com.bridgeintelligent.tag.combination.pojo.*;
import com.bridgeintelligent.tag.combination.service.CombinationService;
import com.bridgeintelligent.tag.constants.ExceptionCodes;
import com.bridgeintelligent.tag.utils.PasswordHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "组合标签管理")
@AllArgsConstructor
@RestController
@RequestMapping("/api/combination")
@Slf4j
public class CombinationController {

    private CombinationService combinationService;

    //private CustomersMapper customersMapper;

    @ApiOperation("修改组合标签")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", name = "combinationModel", value = "组合标签信息")
    })
    @PostMapping("/update")
    public Result updateCustomers(@RequestBody CombinationModel combinationModel) {
        try {
            //校验组合标签名是否超过长度
            if (combinationModel.getCombinationName().length() > 100) {
                throw new CombinationException(ExceptionCodes.COMBINATION_80001);
            }
            if (PasswordHelper.checkSpecial(combinationModel.getCombinationName())){
                return new Result(-1, "名字含有特殊字符");
            }
            //校验组合标签名是否重复
            boolean success = combinationService.checkCombinationName(combinationModel.getCombinationName());
            if (success) {
                combinationService.updateCombination(combinationModel);
            } else {
                //查询组合标签名是否修改
                String oldCombinationName = combinationService.findCombinationNameById(combinationModel.getCombinationId());
                //原来用户未修改用户名
                if (oldCombinationName.equals(combinationModel.getCombinationName())) {
                    //修改用户
                    combinationService.updateCombination(combinationModel);
                } else {
                    return new Result(-1, "组合标签名称重复，请修改组合标签名称后重新提交！");
                }
            }
            return new Result(CombinationCodes.SUCCESS);
        } catch (CombinationException e) {
            return new Result(e.getCode(), "操作失败");
        }
    }

//    @CrossOrigin(origins = "*")
    @ApiOperation("新增组合标签")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "combinationModel", value = "组合标签信息")
    })
    @PostMapping("/add")
    public Result addCustomers(@RequestBody CombinationModel combinationModel) {
        //CombinationModel combinationModel = reqParams();
        try {
            //校验组合标签名是否超过长度
            if (combinationModel.getCombinationName().length() > 100) {
                throw new CombinationException(ExceptionCodes.COMBINATION_80001);
            }
            if (PasswordHelper.checkSpecial(combinationModel.getCombinationName())){
                return new Result(-1, "名字含有特殊字符");
            }
            //校验组合标签名是否重复
            boolean success = combinationService.checkCombinationName(combinationModel.getCombinationName());
            if (success) {
                log.info("前端封装的赛选条件参数："+combinationModel.getQueryCriteria());
                //新建组合标签
                combinationService.addCombination(combinationModel);
            } else {
                return new Result(-1, "组合标签名称重复，请修改组合标签名称后重新提交！");
            }

            return new Result(CombinationCodes.SUCCESS);
        } catch (CombinationException e) {
            return new Result(e.getCode(), "操作失败");
        }
    }

    /**
     * 删除组合标签
     *
     * @return
     */
    @ApiOperation("删除组合标签")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "combinationId", value = "组合标签id")})
    @GetMapping("/delCombination")
    public Result delCombination(String combinationId) {
        combinationService.delCombination(combinationId);
        return new Result(CombinationCodes.SUCCESS);
    }

    /**
     * 获取单个客群的详细信息
     *
     * @return
     */
    @ApiOperation("获取单个组合标签详细信息")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "combinationId", value = "组合标签id")
    })
    @GetMapping("/findOneById")
    public Result findOneById(String combinationId) {
        Combination combination = combinationService.findOneById(combinationId);
        return new Result(CombinationCodes.SUCCESS, combination);
    }

    /**
     * 获取组合标签列表
     *
     * @return
     */
    @ApiOperation("获取组合标签列表")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "pageNumber", value = "页码"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "条数"),
            @ApiImplicitParam(paramType = "query", name = "combinationName", value = "组合标签名称"),
            @ApiImplicitParam(paramType = "query", name = "status", value = "审批状态"),
            @ApiImplicitParam(paramType = "query", name = "uptTimeStart", value = "更新时间筛选（开始）"),
            @ApiImplicitParam(paramType = "query", name = "uptTimeEnd", value = "更新时间筛选（结束）")
    })
    @GetMapping("/list")
    public Result list(Integer pageNumber, Integer pageSize, String combinationName, String status,  String uptTimeStart, String uptTimeEnd) {
        pageNumber = pageNumber == null ? 1 : pageNumber;
        pageSize = pageSize == null ? 10 : pageSize;
        return combinationService.list(pageNumber, pageSize, combinationName, status,  uptTimeStart, uptTimeEnd);
    }

    /**
     * 保存SQL数据
     *
     * @return
     */
    @ApiOperation("保存SQL数据")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "combinationId", value = "组合标签ID")
    })
    @GetMapping("/saveSQL")
    public Result saveSQL(String combinationId) {
        combinationService.saveCombinationData(combinationId);

        return new Result(0);
    }

    /**
     * 删除SQL
     *
     * @return
     */
    @ApiOperation("删除SQL数据")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "combinationId", value = "组合标签id")})
    @GetMapping("/delSQL")
    public Result delSQL(String combinationId) {
        combinationService.delCombinationData(combinationId);
        return new Result(CombinationCodes.SUCCESS);
    }


    public  CombinationModel reqParams() {
        CombinationModel combinationModel = new CombinationModel();
        combinationModel.setCombinationName("新建组合标签21");
        combinationModel.setCombinationDes("测试描述21");
        combinationModel.setScenarious("测试场景x");
        combinationModel.setDepartId("802");
        combinationModel.setDefaultName("否");

        QueryModel model = new QueryModel();
        model.setGroupNum("1");
        model.setLabitemCode("0");
        model.setLabitemName("结果");
        List<String> fields = new ArrayList<>();
        fields.add("001");
        model.setFields(fields);


        FilterGroup filterGroup = new FilterGroup();
        filterGroup.setSymbol("and");

        /*Filter filter1 = new Filter();
        filter1.setDimId("003");
        filter1.setDimName("年收入");
        List<String> valueList1 = new ArrayList<>();
        valueList1.add("1000");
        filter1.setValueList(valueList1);
        filter1.setType("greater");
        filter1.setClassify("03");
        filter1.setTimeType("true");
        filter1.setDataDate("202003");
        filter1.setColName("income");
*/
        Filter filter2 = new Filter();
        filter2.setDimId("001");
        filter2.setDimName("性别");
        List<String> valueList2 = new ArrayList<>();
        valueList2.add("0");
        filter2.setValueList(valueList2);
        filter2.setType("equal");
        filter2.setClassify("02");
        filter2.setTimeType("false");
        filter2.setDataDate("202002");
        filter2.setColName("sex");

        List<Filter> filterList = new ArrayList<>();
        //filterList.add(filter1);
        filterList.add(filter2);

        filterGroup.setFilters(filterList);

        List<FilterGroup> children = new ArrayList<>();
        filterGroup.setChildren(children);
        filterGroup.setLocation("0");

        model.setFilterGroup(filterGroup);

        List<QueryModel> qmList = new ArrayList<>();
        qmList.add(model);
        String json = JSON.toJSONString(qmList);
        //String json = "[{\"filterGroup\":{\"symbol\":\"and\",\"filters\":[{\"dimName\":\"性别\",\"dimId\":\"gender_cd\",\"valueList\":[\"M\"],\"type\":\"equal\",\"id\":\"\",\"classify\":\"02\",\"dataDate\":0,\"timeType\":true,\"staticVal\":\"\",\"dataName\":\"当前月份\",\"yearValue\":\"\",\"dynamicValue\":0,\"timeShow\":true}],\"children\":[],\"location\":\"0\"},\"labitemName\":\"1\",\"labitemCode\":\"1\",\"groupNum\":1}]";
        System.out.println("JSON="+json);
        combinationModel.setQueryCriteria(json);
        return  combinationModel;
    }

}